import re

from django.shortcuts import render, redirect, HttpResponse
from django.core.validators import ValidationError, RegexValidator
from django import forms
from django.conf import settings
from django.db.models import Q


# Create your views here.
from app01 import models
from app01.utils.hashlib_func import set_md5
from app01.utils.page import MyPagenation



def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')  # 自定义验证规则的时候，如果不符合你的规则，需要自己发起错误


class RegisterForm(forms.Form):
    username = forms.CharField(
        max_length=16,
        min_length=6,
        label='用户名',
        widget=forms.widgets.TextInput(attrs={'class': 'username', 'autocomplete': 'off', 'placeholder': '用户名'}),
        error_messages={
            'required': '用户名不能为空！！',
            'max_length': '用户名不能大于16位！！',
            'min_length': '用户名不能小于6位！！',
        }

    )

    password = forms.CharField(
        max_length=32,
        min_length=6,
        label='密码',
        widget=forms.widgets.PasswordInput(
            attrs={'class': 'password', 'placeholder': '输入密码', 'oncontextmenu': 'return false',
                   'onpaste': 'return false'}),
        error_messages={
            'required': '密码不能为空！！',
            'max_length': '密码不能大于32位！！',
            'min_length': '密码不能小于6位！！',
        }
    )

    r_password = forms.CharField(
        label='确认密码',
        widget=forms.widgets.PasswordInput(
            attrs={'class': 'password', 'placeholder': '请再次输入密码', 'oncontextmenu': 'return false',
                   'onpaste': 'return false'}),
        error_messages={
            'required': '确认密码不能为空！！',
        }
    )

    email = forms.EmailField(
        label='邮箱',
        error_messages={
            'required': '邮箱不能为空！！',
            'invalid': '邮箱格式错误！！'
        },
        widget=forms.widgets.TextInput(attrs={'type': 'email',
                                              'class': 'email', 'placeholder': '输入邮箱地址',
                                              'oncontextmenu': 'return false'}),
    )

    telephone = forms.CharField(
        label='手机号',
        max_length=15,
        min_length=11,
        validators=[mobile_validate],
        error_messages={
            'required': '手机号不能为空！！',
        },
        widget=forms.widgets.TextInput(attrs={'class': 'phone_number', 'placeholder': '输入手机号', 'id': 'number',
                                              'autocomplete': 'off'}),
    )

    def clean(self):
        value = self.cleaned_data
        password = value.get('password')
        r_password = value.get('r_password')
        if password == r_password:
            return value
        else:
            self.add_error('r_password', '两次密码不一致！！')
            raise ValidationError('两次密码不一致！！')


# 注册
def register(request):
    if request.method == 'GET':
        register_form_obj = RegisterForm()
        return render(request, 'register.html', {'register_form_obj': register_form_obj})
    else:
        register_form_obj = RegisterForm(request.POST)
        if register_form_obj.is_valid():
            register_form_obj.cleaned_data.pop('r_password')
            password = register_form_obj.cleaned_data.pop('password')

            # 对密码进行加密
            password = set_md5(password)
            register_form_obj.cleaned_data.update({'password': password})
            models.UserInfo.objects.create(**register_form_obj.cleaned_data)
            return redirect('login')
        else:
            return render(request, 'register.html', {'register_form_obj': register_form_obj})


# 登录
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = models.UserInfo.objects.filter(username=username, password=set_md5(password)).first()
        if user_obj:
            return redirect('home')
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误！！'})


# 首页
def home(request):
    return render(request, 'starter.html')


#首页中分页逻辑
def customers(request):

    get_data= request.GET.urlencode()  #search_field=qq__contains&kw=123456

    #搜索客户信息
    search_field = request.GET.get('search_field')  #查询字段
    # print(search_field)  #qq__contains  name__contains
    kw = request.GET.get('kw')  #查询关键字

    if kw:
        # customer_list = models.Customer.objects.filter(Q(qq__contains=kw) | Q(name__contains=kw))
        # customer_list = models.Customer.objects.filter(**{search_field:kw}) 只能做and的关系
        q_obj = Q()
        q_obj.connector = 'or'   #指定q条件查询的连接符Q(name=kw) | Q(qq=kw)  默认是and
        q_obj.children.append((search_field,kw))  #Q(name=kw)
        customer_list = models.Customer.objects.filter(q_obj)
    else:
        customer_list = models.Customer.objects.all()


    # 当前页
    page_num = request.GET.get('page')  #当前页码
    base_url = request.path  # 访问的路径
    # 总数据
    customer_count = customer_list.count()

    per_page_num = settings.PER_PAGE_NUM  # 每页的数量
    page_num_show = settings.PAGE_NUM_SHOW  # 页码数

    page_obj = MyPagenation(page_num,customer_count,base_url,get_data,per_page_num,page_num_show)
    page_html = page_obj.page_html()
    customer_objs = customer_list.reverse()[page_obj.start_data_num:page_obj.end_data_num]
    return render(request, 'saleshtml/customers.html', {'customer_objs': customer_objs, 'page_html': page_html})




class CustomerForm(forms.ModelForm):

    class Meta:
        model = models.Customer
        fields = '__all__'
        error_messages = {
            'qq':{'required':'不能为空'},
            'course':{'required':'不能为空'},
        }
        widgets = {
            'birthday':forms.widgets.TextInput(attrs={'type': 'date'})
        }

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        from multiselectfield.forms.fields import MultiSelectFormField
        for field_name,field in self.fields.items():
           if not isinstance(field,MultiSelectFormField):
               field.widget.attrs.update({'class':'form-control'})

# #添加客户信息
# def add_customers(request):
#     if request.method == 'GET':
#         customer_form = CustomerForm()
#         return render(request, 'saleshtml/add_customers.html', {'customer_form': customer_form})
#     else:
#         customer_form = CustomerForm(request.POST)
#         if customer_form.is_valid():
#             customer_form.save()
#             return redirect('customers')
#         else:
#             return render(request, 'saleshtml/add_customers.html', {'customer_form': customer_form})
#
#
# #编辑客户信息
# def edit_customers(request,c_id):
#     customer_obj = models.Customer.objects.filter(id=c_id).first()
#     if request.method == 'GET':
#         customer_form = CustomerForm(instance=customer_obj)
#         return render(request, 'saleshtml/edit_customers.html', {'customer_form': customer_form})
#     else:
#         customer_form = CustomerForm(request.POST,instance=customer_obj)
#         if customer_form.is_valid():
#             customer_form.save()
#             return redirect('customers')
#         else:
#             return render(request, 'saleshtml/edit_customers.html', {'customer_form': customer_form})




#添加和编辑客户

#添加和编辑客户信息
def add_edit_customer(request,c_id=None):
    # if request.is_ajax()  判断是否是ajax请求

    label = '编辑客户' if c_id else '添加客户'
    customer_obj = models.Customer.objects.filter(id=c_id).first()
    if request.method == 'GET':
        customer_form = CustomerForm(instance=customer_obj)
        return render(request, 'saleshtml/edit_customers.html', {'customer_form': customer_form,'label':label})
    else:
        customer_form = CustomerForm(request.POST,instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            return redirect('customers')
        else:
            return render(request, 'saleshtml/edit_customers.html', {'customer_form': customer_form,'label':label})